package com.opensource.component.clickhorse.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import ru.yandex.clickhouse.ClickHouseDataSource;

import javax.sql.DataSource;

/**
 * @author ZonLen since on 2021/4/5 上午9:35
 */
@ConditionalOnProperty(name = "spring.datasource.click.enable", havingValue = "true")
@EnableConfigurationProperties(ClickHorseProperty.class)
public class ClickHorseAutoConfiguration {

  @Bean
  public DataSource dataSource(ClickHorseProperty clickHorseProperty) {
    DruidDataSource datasource = new DruidDataSource();
    datasource.setUrl(clickHorseProperty.getUrl());
    datasource.setDriverClassName(clickHorseProperty.getDriverClassName());
    datasource.setInitialSize(clickHorseProperty.getInitialSize());
    datasource.setMinIdle(clickHorseProperty.getMinIdle());
    datasource.setMaxActive(clickHorseProperty.getMaxActive());
    datasource.setMaxWait(clickHorseProperty.getMaxWait());
    return datasource;
  }

  @Bean
  @ConditionalOnBean(DataSource.class)
  public SqlSessionFactory clickHouseSqlSessionFactoryBean(DataSource dataSource) throws Exception {
    SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
    factory.setDataSource(dataSource);
    // 实体 model的 路径 比如 com.order.model
    factory.setTypeAliasesPackage("com.opensource.component.clickhorse.mapper");
//    //添加XML目录
    ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    factory.setMapperLocations(resolver.getResources("classpath:mapper/*.xml"));
    //开启驼峰命名转换
    factory.getObject().getConfiguration().setMapUnderscoreToCamelCase(true);
    return factory.getObject();
  }
}
